package com.hxz.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库连接工具类
 */
public class JDBCUtil {
    //数据库连接
    private static String url = null;
    //数据库用户名
    private static String user = null;
    //数据库密码
    private static String password = null;
    //数据库驱动
    private static String driver = null;

    //静态代码加载类
    static {
        Properties properties = new Properties();
        InputStream in = JDBCUtil.class.getResourceAsStream("/jdbc.properties");
        try {
            properties.load(in);
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //开发数据库连接方法
    public static Connection getConn() throws SQLException {
        Connection connection = DriverManager.getConnection(url, user, password);
        return  connection;
    }

    //关闭处理
    public static void closeAll(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("closeAll");
    }
}
